# od 结果输出路径
# config_file 配置文件路径
if (F) {
    suppressMessages(library(tidyverse))
    suppressMessages(library(magrittr))
    library(furrr)

    od <- "/Pub/Users/wangyk/project/Poroject/F230220003_Fe/out/4.ducking/PGD/"
    dir.create(od)
    config_file <- "/Pub/Users/wangyk/project/Poroject/F230220003_Fe/out/4.ducking/PGD/ducking_config.txt"
    setwd(od)
    pdbqt_files <- list.files("/Pub/Users/wangyk/project/Poroject/Molecular_ducking/pdbqt_file", pattern = "pdbqt", full.names = T)
    drug_name <- str_split(pdbqt_files, "/") %>%
        map_chr(~ .x[9]) %>%
        str_remove("\\.pdbqt")
    ducking_res_od <- file.path(od, drug_name)
    plan(multicore, workers = 8)

    ducking <- \(x, y, z) {
        dir.create(y, showWarnings = F, recursive = T)
        system2(
            command = "/Pub/Users/wangyk/miniconda3/envs/Molecular_docking/bin/vina",
            args = c(
                str_glue("--config {config_file}"),
                str_glue("--ligand {x}"),
                str_glue("--out {y}/out.pdbqt"),
                str_glue("--receptor /Pub/Users/wangyk/project/p/额外补充分子对接2_F230727003/ZBP1/2l4m_ZBP1_model1.pdbqt"),
                str_glue("--exhaustiveness 20"),
                str_glue("--num_modes 5"),
                str_glue("--cpu 4"),
                str_glue("--energy_range 4"),
                str_glue("--log {y}/{z}_log.txt")
            )
        )
    }
    furrr::future_pwalk(list(pdbqt_files, ducking_res_od, drug_name), ducking)
}


# 文件筛选，筛选结合能最小的构象
list.files(
    "out/4.ducking/PGD", "\\.txt",
    recursive = T, full.names = T
) -> file_dirs


res <- map(seq_along(file_dirs), function(i) {
    if (str_detect(file_dirs[i], "config")) {
        return(0)
    }

    reading <- file_dirs[i] %>%
        read_lines(skip = 22,progress = F)

    reading[4:{
        which(reading == "Writing output ... done.") - 1
    }] %>%
        str_split(" ") -> a

    map(a, ~ which(.x != "")) -> index

    res <- map2(a, index, ~ .x[.y]) %>%
        map(., ~ .x[2]) %>%
        unlist() %>%
        as.numeric() %>%
        .[1]

    return(res)
}, .progress = T)


names(res) <- seq_along(res)
sort(unlist(res)) %>% head

file_dirs[638]

